package cn.shop.dys.activity;


import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RatingBar;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;


import java.util.ArrayList;
import java.util.List;

import cn.shop.dys.bean.productdetail.ProductData;
import cn.shop.dys.bean.productdetail.ProductDetail;
import cn.shop.dys.constant.CommonConstant;
import cn.shop.dys.constant.DetaiConstants;
import cn.shop.dys.constant.SPConstant;
import cn.shop.dys.fragment.ProductDetailsFragment;
import cn.shop.dys.fragment.ProductRelativeFragment;
import cn.shop.dys.fragment.ProductUserCommontsFragment;
import cn.shop.dys.fragment.QFragment;
import cn.shop.dys.util.ComUtil;
import cn.shop.dys.util.SPUtil;
import cn.shop.lib_common.CommonUtil;
import cn.shop.lib_common.wiget.SlidingUpPanelLayout.SlidingUpPanelLayout;
import cn.shop.lib_common.wiget.autorollLayout.AutoRollLayout;
import cn.shop.dys.R;
import cn.shop.lib_common.wiget.autorollLayout.bean.IRollItem;

//import fei.itcast.cn.productdetails.bean.Product;

/**
 * Created by Administrator on 2016/4/19.
 */
public class ProductActivity extends AppCompatActivity implements View.OnClickListener, RadioGroup.OnCheckedChangeListener {
    static String EXTRA_INT = "pId";
    private ImageButton bt01, bt02;
    private EditText edt;
    private int num = 1;
    private List<ImageView> startsList;
    private TextView oldPrice, nowPrice;
    private AutoRollLayout arl;
    private ScrollView mScrollView;
    private int downY;

    private ProductDetail product;
    private String url;
    private int pId;
    private SlidingUpPanelLayout supl;

    private RadioGroup radioGroup;
    List<Fragment> fragments = new ArrayList<>();
    private TextView headTitle;
    private Spinner spinner;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_head);

//        ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item);
//        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//        spinner = (Spinner) findViewById(R.id.product_ml_count_sp);
//        spinner.setAdapter(new Myadapter());

        supl = (SlidingUpPanelLayout) findViewById(R.id.sliding_layout);
        supl.addPanelSlideListener(new SlidingUpPanelLayout.PanelSlideListener() {
            @Override
            public void onPanelSlide(View panel, float slideOffset) {

            }

            @Override
            public void onPanelStateChanged(View panel, SlidingUpPanelLayout.PanelState previousState, SlidingUpPanelLayout.PanelState newState) {

            }
        });
        supl.setPanelHeight(0);

        Intent intent = getIntent();
        pId = intent.getIntExtra("pId", 1);
        url = CommonConstant.HOST + "/product?pId=" + pId;

        bt01 = (ImageButton) findViewById(R.id.reduce);
        bt02 = (ImageButton) findViewById(R.id.add);
        edt = (EditText) findViewById(R.id.edt);
        oldPrice = (TextView) findViewById(R.id.product_old_price);
        //设置横划线
        oldPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        nowPrice = (TextView) findViewById(R.id.product_preferential_price);
        arl = (AutoRollLayout) findViewById(R.id.activity_product_arl);
        mScrollView = (ScrollView) findViewById(R.id.product_detail_sl);
//        View iv_favarite = findViewById(R.id.iv_favarite);


        mScrollView.setOnTouchListener(new myScrollViewTouchListener());
        downLoadData();


    }

    private void initFragment() {
        headTitle = (TextView) findViewById(R.id.productCenter_title);
        radioGroup = (RadioGroup) findViewById(R.id.product_main_rg);
        radioGroup.setOnCheckedChangeListener(this);

        fragments.add(new ProductDetailsFragment());
        fragments.add(new QFragment());
        fragments.add(new ProductRelativeFragment());
        ((RadioButton) radioGroup.getChildAt(0)).setChecked(true);
    }

    private void downLoadData() {
        HttpUtils httpUtils = new HttpUtils();
        httpUtils.send(HttpRequest.HttpMethod.GET, url, callBack);
    }


    String productDescFinal;
    private RequestCallBack<String> callBack = new RequestCallBack<String>() {
        @Override
        public void onSuccess(ResponseInfo<String> responseInfo) {
            String result = responseInfo.result;
            Log.e("product", " " + result);
            Gson gson = new Gson();
            ProductData productData = gson.fromJson(result, ProductData.class);
            Log.e("product", " " + productData);
            product = productData.getProduct();

            productDescFinal = productData.getProduct().getProductDesc();
            initData();
            initFragment();
        }

        @Override
        public void onFailure(HttpException e, String s) {
            Log.e("onFailure", "失败了");
        }
    };

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        String[] title = {"商品详情", "用户评价", "相关推荐"};
        View checked = group.findViewById(checkedId);
        int index = group.indexOfChild(checked);
        headTitle.setText(title[index]);
        Fragment fragment = fragments.get(index);
        android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.main_fragment_container, fragment).commit();

    }

    private class myScrollViewTouchListener implements View.OnTouchListener {
        boolean isScroll;

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    downY = (int) event.getY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    int scrollY = v.getScrollY();//ScrollView顶端已经滑出去的高度
                    int height = v.getHeight();//ScrollView的可见高度
                    int scrollViewMeasuredHeight = mScrollView.getChildAt(0).getMeasuredHeight();
                    //滑动到了顶端
                    if (scrollY == 0) {

                    }
                    //滑动到了底部 && height < downY
                    if ((scrollY + height) == scrollViewMeasuredHeight) {
                        isScroll = true;
                        supl.setPanelState(SlidingUpPanelLayout.PanelState.EXPANDED);

                    }
                    break;
                case MotionEvent.ACTION_UP:
                    if (isScroll) {
                        supl.setPanelState(SlidingUpPanelLayout.PanelState.EXPANDED);
                        isScroll = false;
                    }
                    break;
                default:
                    break;
            }
            return false;
        }
    }

    private void initData() {
        init();//初始化商品数量选择开关   商品id："product":{id}
        initArl();//设置商品轮播图图片       "product":{"pics":["url","ur2"],}//里面还有"bigPic":[ url1,url2 ]

        //设置名称       "name": "韩版时尚蕾丝裙",
        TextView name = (TextView) findViewById(R.id.product_instruction_tv);
        name.setText(product.getName());

        //设置价格     "marketPrice": "500" //市场价"price": "350" //会员价
//        TextView oldPrice = (TextView) findViewById(R.id.product_old_price);
//        TextView newPrice = (TextView) findViewById(R.id.product_preferential_price);
        oldPrice.setText("¥" + (int) product.getMarketPrice() + ".00");
        nowPrice.setText("¥" + (int) product.getPrice() + ".00");

        //设置星级数"score": "5",
        showStarscore((int) product.getScore());

        //设置规格ml    用"buyLimit":10     //单品购买上限
//        TextView mlCount = (TextView) findViewById(R.id.product_ml_count);
//        mlCount.setText(product.getBuyLimit() + "ml");

        //设置配送地 "inventoryArea":"全国",  //配货说明
        TextView sendArea = (TextView) findViewById(R.id.product_send_area);
        sendArea.setText("查看库存:" + product.getInventoryArea() + "有货");

        //设置评论"commentCount":1,   //商品评论数
        TextView commentCount = (TextView) findViewById(R.id.product_commentCount);
        commentCount.setText("用户评价:共有" + product.getCommentCount() + "人评价");

        TextView product_descript = (TextView) findViewById(R.id.product_descript_tv);
//        product_descript.setText();

    }

    //TODO 传入商品url
    private void initArl() {
        List<IRollItem> items = new ArrayList<>();
        for (final String p : product.getPics()) {
            items.add(new IRollItem() {

                @Override
                public String getRollItemImageUrl() {

                    return DetaiConstants.HOST + p;
                }

                @Override
                public String getTitle() {
                    return "";
                }
            });
        }

//        items.add(new RollItem("","http://192.168.56.1:80/market/images/product/detail/bigcar1.jpg"));
//        items.add(new RollItem("","http://192.168.56.1:80/market/images/product/detail/bigcar2.jpg"));
//        items.add(new RollItem("","http://192.168.56.1:80/market/images/product/detail/bigcar3.jpg"));
//        items.add(new RollItem("","http://192.168.56.1:80/market/images/product/detail/bigcar4.jpg"));
//        items.add(new RollItem("",product.getPics()));
//        items.add(new RollItem("","R.drawable.product2"));
//        items.add(new RollItem("","R.drawable.product3"));

        arl.setAutoRoll(false);

        arl.setOnClickListener(this);
        arl.setItems(items);
        arl.setAutoRoll(true);
    }

    private void showStarscore(int score) {
        RatingBar starRB = (RatingBar) findViewById(R.id.product_star_rb);
        starRB.setRating(product.getScore());
    }

    private void init() {
        bt01.setTag("+");
        bt02.setTag("-");

        edt.setInputType(android.text.InputType.TYPE_CLASS_NUMBER);
        edt.setGravity(Gravity.CENTER);
        edt.setText(String.valueOf(num));
        setViewListener();
    }

    private void setViewListener() {
        bt01.setOnClickListener(new OnButtonClickListener());
        bt02.setOnClickListener(new OnButtonClickListener());
        edt.addTextChangedListener(new OnTextChangeListener());
    }


    @Override
    public void onClick(View v) {
    }

    public void returnToMain(View v) {
        //TODO 点击返回
        onBackPressed();
    }

    public void intoShopCar(View v) {
        //TODO 点击加入购物车,跳转购物车界面

        Intent intent = new Intent(this,MainActivity2.class);
        intent.putExtra("mainIndex",2);
        startActivity(intent);

    }

    public void addCard(View v) {
        //TODO 点击加入购物车，不跳转购物车界面
        //获取pid和商品数量  传给购物车界面
        int id = product.getId();
        int productNum = Integer.parseInt(String.valueOf(edt.getText()));
        String userId = SPUtil.getString(this, SPConstant.USER_INFO_USER_ID);


        ComUtil.proToCartDB(userId,id,productNum,"1,3");
        CommonUtil.showSingleToast(this,"添加成功");


    }


    public void buyRightNow(View v) {
        //TODO 点击立即购买
//        Intent intent=new Intent(this, MainActivity.class);
//        startActivity(intent);
        int id = product.getId();
        int productNum = Integer.parseInt(String.valueOf(edt.getText()));
        String userId = SPUtil.getString(this, SPConstant.USER_INFO_USER_ID);
        if (TextUtils.isEmpty(userId)){return;}
        Intent intent = new Intent(this,PayCenterActivity.class);
        intent.putExtra("cartToBill",id+":"+productNum+":1,3");
        startActivity(intent);


    }


    //TODO 点击收藏
    public boolean b_focus;
    public void intoFavorite(View v) {
        b_focus=!b_focus;
        ImageView product_focus_iv = (ImageView) findViewById(R.id.product_focus_iv);
        TextView product_focus_tv = (TextView) findViewById(R.id.product_focus_tv);
        product_focus_iv.setImageResource(b_focus?R.drawable.product_heart:R.drawable.product_heart_empty);
        product_focus_tv.setText(b_focus?"已关注":"关注");
    }

    public class OnButtonClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            String numString = edt.getText().toString();
            if (numString == null || numString.equals("")) {
                num = 0;
                edt.setText("0");
            } else {
                if (v.getTag().equals("-")) {
                    if (++num < 0) {
                        num--;
                        num = 1;
//                        Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show();
                    } else {
                        edt.setText(String.valueOf(num));
                    }
                } else if (v.getTag().equals("+")) {
                    if (--num < 1) {
                        num++;
                        num = 1;
//                        Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show();
                    } else {
                        edt.setText(String.valueOf(num));
                    }
                }
            }
        }
    }

    class OnTextChangeListener implements TextWatcher {
        @Override
        public void afterTextChanged(Editable s) {
            String numString = s.toString();
            if (numString == null || numString.equals("")) {
                num = 0;
            } else {
                int numInt = Integer.parseInt(numString);
                if (numInt < 0) {
                    numInt = 1;
//                    Toast.makeText(MainActivity.this, "请输入一个大于0的数字", Toast.LENGTH_SHORT).show();
                } else {
                    edt.setSelection(edt.getText().toString().length());
                    num = numInt;
                }
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    }


//    private class Myadapter implements SpinnerAdapter {
//    }
}
